package book.wirte;

import java.io.IOException;
import java.util.Date;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import oracle.net.aso.i;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;

import book.dao.impl.BookDaoImpl;
import book.pojo.Book;
import book.read.BookReadMulti;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class BookWriteThread implements Runnable {

	public void run() {
		// TODO Auto-generated method stub
		ConnectionFactory factory=new ActiveMQConnectionFactory("tcp://10.222.29.152:61616");
		Destination queueDestination=new ActiveMQQueue("books");
		Connection connection=null;
		Session session=null;
		MessageProducer mp=null;
		try {
			connection = factory.createConnection();
			connection.start();
			session=connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
			mp=session.createProducer(queueDestination);
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		ObjectMapper oMapper=new ObjectMapper();
		
		int count=0;
		Book temp=new Book();
		Long startLong=System.currentTimeMillis();
		while(BookWriteMulti.i<10000)
		{
			synchronized (BookReadMulti.i){
				temp.setId(BookWriteMulti.i);
				temp.setName("name"+BookWriteMulti.i);
				temp.setPub_date(new Date(System.currentTimeMillis()+BookWriteMulti.i*100000));
				temp.setIs_new((BookWriteMulti.i%2)==0?true:false);
				temp.setAuthor("how Knows");
				temp.setPrice(Math.random()*1000);
				temp.setPublisher("Peking");
				try {
					TextMessage msg=session.createTextMessage(oMapper.writeValueAsString(temp));
					mp.send(msg);
					BookWriteMulti.i++;
				} catch (JsonProcessingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (JMSException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				count++;
			}
		}
		try {
			mp.close();
			session.close();
			connection.close();
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Long endLong=System.currentTimeMillis();
		System.out.println("has wirte "+count+" books...");
		System.out.println(endLong-startLong);
	}
}
